<?php
class image extends Model{
	public static function getTableName(){
		return 'image';
	}

	/*
	 * by donald
	 * at 2010-10-27
	 */
	public function set($object)
	{
		$this->programme_id = $object->programme_id;
		$this->episode_id = $object->episode_id;
		$this->ii_id = $object->ii_id;
		$this->ii_status = $object->ii_status;
		$this->original_filename = $object->original_filename;
		$this->thumbnail_url = $object->thumbnail_url;
		$this->source_url = $object->source_url;
		$this->casts = $object->casts;
		$this->tags = $object->tags;
		$this->country_allow_list = $object->country_allow_list;
		$this->country_deny_list = $object->country_deny_list;
		$this->publish_datetime = $object->publish_datetime;
		$this->expire_datetime = $object->expire_datetime;
		$this->copyright = $object->copyright;
		$this->mdes_status = $object->mdes_status;
		$this->status = $object->status;
		$this->created_at = $object->created_at;
		$this->created_by = $object->created_by;
		$this->modified_at = $object->modified_at;
		$this->modified_by = $object->modified_by;
	}

	public function getResultList($findRelation, $field, $operation, $value, $start, $length, $sidx = NULL, $sord = NULL, $unpublish = 0)
	{
		$find	=	$findRelation['mapField'];
		$db_con = ($unpublish == 1) ? CommonUtils::getDbConn(0,'preview') : Model::$dbo['r'];
        # first, deal with title party!
        $titleWhere =   $programmeTitleIds  =   NULL;
        $pathWhere  =   NULL;
        $imageWhere =   NULL;
        $searchSing =   FALSE;
        $programmes =   array();
		$where      =   array();
        $resField   =   $resOperation   =   $resValue   =   array();
        $folder_images = $images = array();

        foreach ($field as  $fieldKey=>$fieldValue) {
            switch ($fieldValue) {
                case 'title':
                    $titleWhere[] = Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                    break;
                case 'path':
                    $pathWhere[] = Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                    break;
                case 'image_title':
                    $imageWhere[] = Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
                    break;
                case 'folder_id':
                    $folder_image_new = folder_item::getItemByFolderId($value[$fieldKey]);
                    $folder_images = array_merge($folder_images, $folder_image_new);
                    break;
                default:
                    $resField[$fieldKey]    =   $fieldValue;
                    $resOperation[$fieldKey]=   $operation[$fieldKey];
                    $resValue[$fieldKey]    =   $value[$fieldKey];
            }
        }

        if (!empty($titleWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByTitle($titleWhere,$field,$operation);
        }

        if (!empty($pathWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByPath($pathWhere);
        }

        if (!empty($imageWhere)) {
			$images = CommonUtils::getMediaIdsByTitle('image',$imageWhere,$field,$operation);
            if (empty($images)) {
                $where[] = 'id IS NULL';
            }
        }

        if (!empty($images) && !empty($folder_images)) {
            $all_images = array_intersect($images, $folder_images);
            if (!empty($all_images)) {
                $where[] = "id IN (" . implode(',', $all_images) . ")";
            } else {
                $where[] = 'id IS NULL';
            }
        } else if (!empty($images)) {
			$where[] = 'id in('. implode(',',$images) .')';
        } else if (!empty($folder_images)) {
            $where[] = "id IN (" . implode(',', $folder_images) . ")";
        } else if (array_search('folder_id', $field) !== FALSE) {
            $where[] = 'id IS NULL';
        }

        if ($searchSing)
        {
			if (count($programmes)>1){
				$programmes = call_user_func_array('array_intersect',$programmes);
			}else{
				$programmes = $programmes[0];
			}
			$programmeTitleIds = implode(',', $programmes);   
            if (empty($programmeTitleIds))  $programmeTitleIds  =   '""';
            $programmeTitleIds  =   ' WHERE image.programme_id IN ('. $programmeTitleIds. ')';
        }
		$where[] =	Model::assembleWhereSentence($find, $resField, $resOperation, $resValue);
		$where   = array_filter($where);
		if (!empty($where))
		{
			$where	=	' WHERE '. implode(' and ',$where);
		}else{
			$where  = '';
		}

		$subSql =	'
			SELECT
				image.id											AS	id,
                image.programme_id                                  AS  programme_id,
				(
					SELECT
						GROUP_CONCAT(`programme-language`.title SEPARATOR "\n\t")
					FROM
						image AS inImage LEFT JOIN `programme-language` ON (inImage.programme_id = `programme-language`.programme_id)
					WHERE
						inImage.id = image.id
				)													AS	title,
                (
                    SELECT
                        GROUP_CONCAT(`image-language`.title SEPARATOR "\n\t")
                    FROM
                        image AS inImage LEFT JOIN `image-language` ON (inImage.id = `image-language`.image_id)
                    WHERE
                        inImage.id = image.id
                )                                                   AS  image_title,
				image.status										AS	record_status,
				modified_at,
				image.modified_by									AS	modified_by
			FROM
				image
            '. $programmeTitleIds .'
			GROUP BY id
			';

		$sql=	'
			SELECT
				id,
                programme_id,
                title,
                image_title,
				record_status,
				modified_at,
				modified_by
			FROM
			(
				'. $subSql. '
			)	AS	findApi
			'.	$where;

		# Order By ...
		$orderBy=	$orderTmp   =   NULL;
		if (!empty($sidx)	&&	!empty($find[$sidx]))
		{
			$orderTmp	=	$find[$sidx];
			if ('desc'	==	$sord)
			{
				$orderTmp	.=	' DESC ';
			}
			elseif ('asc'	==	$sord)
			{
				$orderTmp	.=	' ASC ';
            }
            $orderBy[]  =   $orderTmp;
		}

        if (!empty($where))
        {
            foreach ($field as  $value)
            {
                if (empty($find[$value]))   continue;
                if ('path'  ==  $value)     continue;
                $orderBy[]  =   $find[$value];
            }
        }

        if (empty($orderBy))    $orderBy[]  =   '`findApi`.`modified_at` DESC';

        $orderBy    =   ' ORDER BY '. implode(', ', $orderBy);
		$dataSql	=	$sql. $orderBy. ' LIMIT '. $start. ', '. $length;
		$totalSql	=	'SELECT count(*) AS num FROM ('. $sql. ')	AS	tmp';

		$result	=	$db_con->findBySql(__class__,$dataSql);
		$retAll	=	$db_con->findBySql(__class__,$totalSql);

        if (empty($retAll[0]->num)) $retAll[0]->num =   0;
        if (empty($result[0]))      $result         =   array();
		$list	=	array();
		$list['page']	=	ceil($start / $length) + 1;
		$list['total']	=	ceil($retAll[0]->num / $length);
		$list['records']=	$retAll[0]->num;

		foreach	($result	as	$gridData)
		{
			$tmp			=	array();
			$tmp['id']		=	$gridData->id;
			$tmp['cell']	=	array();

			$gridData->title    = explode("\n\t",$gridData->title);
			$gridData->title[0] = htmlentities($gridData->title[0],ENT_QUOTES,'UTF-8');
			$gridData->title[1] = isset($gridData->title[1]) ? htmlentities($gridData->title[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->title    = implode('<br />',$gridData->title);

			$gridData->image_title    = explode("\n\t",$gridData->image_title);
			$gridData->image_title[0] = htmlentities($gridData->image_title[0],ENT_QUOTES,'UTF-8');
			$gridData->image_title[1] = isset($gridData->image_title[1]) ? htmlentities($gridData->image_title[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->image_title    = implode('<br />',$gridData->image_title);

			$gridData->modified_at= str_replace(' ','<br />',$gridData->modified_at);

            $originalStatus =   $gridData->record_status;
            if (!empty($unpublish))
            {
                $publish_log = publish_log::getPublishLog(__class__, $gridData->id);
                if (property_exists($publish_log, 'non_premium')) {
                    $publish = Model::object2array($publish_log->non_premium); 
                } else {
                    $publish = array();
                }

                $gridData->record_status    =   NULL;
                $gridData->modified_by      =   NULL;
                $gridData->modified_at      =   NULL;
                if (isset($publish['action'])   &&  isset(AC::$publicLogAction[$publish['action']]))
                {
                    $gridData->record_status    =   AC::$publicLogAction[$publish['action']];
                    isset($publish['published_by']) &&  $gridData->modified_by  =   $publish['published_by'];
                    isset($publish['published_at']) &&  $gridData->modified_at  =   $publish['published_at'];
                }
            }
            else
            {
                isset(AC::$op_status[$gridData->record_status]) &&  $gridData->record_status    =   AC::$op_status[$gridData->record_status];
            }
			foreach ($find	as	$name	=>	$column)
			{
                if ('programme_id'  ==  $name   ||  'path'  ==  $name)  continue;
                $tmp['cell'][]	=	$gridData->$name;
			}

            $delEdit    =   $delView    =   NULL;
            if (AC::STATUS_DELETED !=   $originalStatus &&  empty($unpublish))
            {
                $delEdit    =	'<a title="Edit" href="get_image.html?act=edit&id='. $gridData->id. '" class="btn edit ui-state-default ui-corner-all"><span class="ui-icon ui-icon-pencil"/>Edit</a>';
            }
            if (empty($unpublish)   ||  (isset($publish['action'])  &&  AC::LOG_OP_PUBLISH  ==  $publish['action']))
            {
                $delView    =   '<a title="View" href="get_image.html?act=view&id='. $gridData->id. '&unpublish='. $unpublish. '" class="btn view ui-state-default ui-corner-all"><span class="ui-icon ui-icon-image"/>View</a>';
            }
            $tmp['cell'][]  =   $delEdit. $delView;
			$list['rows'][]	=	$tmp;
            unset($publish);
		}

		return	$list;
	}

	public function getDetails($id)
	{
        $sql=   '
            SELECT
                image.*,
                GROUP_CONCAT(`programme-language`.title SEPARATOR "\n\t")     AS  programme,
                `image-language`.title  AS  title,
                `image-language`.description    AS  description
            FROM
                image LEFT JOIN `image-language` ON (image.id = `image-language`.image_id)
                LEFT JOIN `programme-language` ON (image.programme_id = `programme-language`.programme_id)
            WHERE
                image.id = "'.$id.'"
            ';
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);

        $sql = "SELECT * FROM `image-language` WHERE `image_id` = " . $id;
        $ro = Model::$dbo['r']->findBySql(__class__, $sql);
        foreach ($ro as $obj) {
            $image_language[$obj->language_id] = $obj;
        }

        $num_language_en = language::getLanguageId(AC::LANGUAGE_EN);
        if (!isset($image_language[$num_language_en])) {
            $image_language[$num_language_en]->title = '';
            $image_language[$num_language_en]->description = '';
        }

        $ret[0]->image_language = $image_language;
        if(isset($ret[0]) && !empty($ret[0]))
        {
            if('ALL' == $ret[0]->country_deny_list)
            {
                $ret[0]->country_allow_list = ParseCountryCode::country2json(AC::COUNTRY_LIST_CODE,$ret[0]->country_allow_list,0);
            }
            else
            {
                $ret[0]->country_deny_list = ParseCountryCode::country2json(AC::COUNTRY_LIST_CODE,$ret[0]->country_deny_list,1);
            }
        }
		return Model::object2array($ret[0]);
    }

    /**
     * get all image(/ID) for programme_id
     * @param   $programme  Int     programme ID
     * @param   $idSwitch   Bool    TRUE : get only image IDs
     * @return  Array
     */
    public static function getImagesForProgramme($programme, $idSwitch = NULL)
    {
        $image  =   array();
        if ($programme < 1) return  $image;

        $sql    =   'SELECt * FROM image WHERE programme_id ="'. $programme. '"';
        $ret    =   Model::object2array(Model::$dbo['r']->findBySql(__class__, $sql));
        if (empty($ret[0])) return  $image;

        foreach ($ret   as  $imageValue)
        {
            $image[$imageValue['id']]   =   empty($idSwitch)    ?   $imageValue :   $imageValue['id'];
        }

        return  $image;
    }

    /**
     * get proofread SQL
     * @param   $id Int
     * @return  Array
     */
    public function getProofread($id)
    {
        if (empty($id)) return  array();
        $sqlArr =   array(
                        'image'             =>  array('id = "'. $id. '"'),
                        'image-language'    =>  array('image_id = "'. $id. '"'),
                    );

        $sqlArray   =   array();
        foreach ($sqlArr    as  $tableName  =>  $whereArray)
        {
            $sqlArray[$tableName]   =   Model::assembleGetProofreadSql($tableName, $whereArray);
        }
        return  $sqlArray;
    }

	/*
	 * by donald
	 */
	public function add_change_log()
	{
		$result = ChangeLogTools::getEpisodeIdsByImageId($this->id);

		$field['type'] = $this->getTableName();
		$field['keys'] = array('id' => $this->id);
		$field['is_active'] = 1;
		$field['programme_id'] = $result['programme_id']; 
		$field['episode_id'] = $result['episode_id']; 
		$field['is_publish'] = 0;

		change_log::updateOne($field);
	}

	/*
	 * by donald
	 */
	public function delete_change_log()
	{
		$type = $this->getTableName();
		$keys = array('id' => $this->id);
		$is_publish = 0;

		change_log::delTypeAndKeysLog($type, $keys, $is_publish);
	}
}
